from pydantic import BaseModel, Field, field_validator
from typing import Optional, List, Dict, Any, Union
from datetime import datetime, date, time
from enum import Enum
import uuid
from .base import BaseResponse


class AuditDecision(str, Enum):
    """审核决策枚举."""
    APPROVED = "approved"
    REJECTED = "rejected"
    CONDITIONAL = "conditional"
    PENDING = "pending"


class AuditorType(str, Enum):
    """审核人类型枚举."""
    AI_SYSTEM = "ai_system"
    HUMAN_REVIEWER = "human_reviewer"
    RULE_ENGINE = "rule_engine"
    HYBRID = "hybrid"


class RulePriority(str, Enum):
    """规则优先级枚举."""
    LOW = "low"
    MEDIUM = "medium"
    HIGH = "high"
    CRITICAL = "critical"


class AuditRequest(BaseModel):
    """审核请求数据模型."""
    
    # 基础信息
    request_id: str = Field(default_factory=lambda: str(uuid.uuid4()), description="审核请求ID")
    
    # 申请人信息
    applicant_info: Dict[str, Any] = Field(..., description="申请人基本信息")
    
    # 申请详情
    classroom_id: str = Field(..., description="教室ID", min_length=1, max_length=50)
    start_time: datetime = Field(..., description="开始时间")
    end_time: datetime = Field(..., description="结束时间")
    usage_purpose: str = Field(..., description="使用目的", min_length=5, max_length=1000)
    participants_count: int = Field(..., description="参与人数", ge=1, le=10000)
    
    # 设备和特殊需求
    equipment_needs: Optional[List[str]] = Field(default=None, description="设备需求列表")
    special_requirements: Optional[Dict[str, Any]] = Field(default=None, description="特殊要求")
    
    # 文档材料
    documents: Optional[List[Dict[str, Any]]] = Field(default=None, description="支持文档列表")
    extracted_content: Optional[Dict[str, str]] = Field(default=None, description="文档提取内容")
    
    # 申请上下文
    application_context: Optional[Dict[str, Any]] = Field(default=None, description="申请上下文信息")
    priority_level: int = Field(default=1, description="优先级", ge=1, le=5)
    
    # 时间戳
    created_at: datetime = Field(default_factory=datetime.now, description="创建时间")
    updated_at: Optional[datetime] = Field(default=None, description="更新时间")
    
    @field_validator('end_time')
    @classmethod
    def validate_time_order(cls, v, info):
        if info.data and 'start_time' in info.data and v <= info.data['start_time']:
            raise ValueError('结束时间必须晚于开始时间')
        return v
    
    @field_validator('start_time')
    @classmethod
    def validate_future_time(cls, v):
        if v <= datetime.now():
            raise ValueError('开始时间必须是未来时间')
        return v


class RuleCondition(BaseModel):
    """规则条件模型."""
    
    field_name: str = Field(..., description="字段名称")
    operator: str = Field(..., description="操作符 (eq, gt, lt, gte, lte, in, not_in, contains)")
    value: Union[str, int, float, List[Any]] = Field(..., description="条件值")
    weight: float = Field(default=1.0, description="权重", ge=0, le=1)


class AuditRule(BaseModel):
    """单个审核规则模型."""
    
    rule_id: str = Field(default_factory=lambda: str(uuid.uuid4()), description="规则ID")
    name: str = Field(..., description="规则名称", min_length=1, max_length=100)
    description: Optional[str] = Field(default=None, description="规则描述", max_length=500)
    
    # 规则条件
    conditions: List[RuleCondition] = Field(..., description="规则条件列表")
    condition_logic: str = Field(default="AND", description="条件逻辑 (AND, OR)")
    
    # 规则结果
    action: str = Field(..., description="规则动作 (approve, reject, flag, score)")
    score_impact: float = Field(default=0, description="分数影响", ge=-100, le=100)
    message: Optional[str] = Field(default=None, description="规则消息")
    
    # 规则属性
    priority: RulePriority = Field(default=RulePriority.MEDIUM, description="规则优先级")
    is_active: bool = Field(default=True, description="是否激活")
    is_blocking: bool = Field(default=False, description="是否为阻塞规则")


class AuditStandard(BaseModel):
    """审核标准模型."""
    
    # 标准基础信息
    standard_id: str = Field(default_factory=lambda: str(uuid.uuid4()), description="标准ID")
    name: str = Field(..., description="标准名称", min_length=1, max_length=100)
    description: Optional[str] = Field(default=None, description="标准描述", max_length=1000)
    version: str = Field(default="1.0", description="版本号")
    
    # 规则集合
    rules: List[AuditRule] = Field(default_factory=list, description="审核规则列表")
    
    # 阈值设置
    auto_approve_threshold: float = Field(default=80.0, description="自动通过阈值", ge=0, le=100)
    auto_reject_threshold: float = Field(default=30.0, description="自动拒绝阈值", ge=0, le=100)
    manual_review_threshold: float = Field(default=50.0, description="人工审核阈值", ge=0, le=100)
    
    # 标准属性
    priority: int = Field(default=1, description="标准优先级", ge=1, le=10)
    is_active: bool = Field(default=True, description="是否激活")
    is_default: bool = Field(default=False, description="是否为默认标准")
    
    # 适用范围
    applicable_contexts: Optional[List[str]] = Field(default=None, description="适用上下文")
    excluded_contexts: Optional[List[str]] = Field(default=None, description="排除上下文")
    
    # 时间戳
    created_at: datetime = Field(default_factory=datetime.now, description="创建时间")
    updated_at: Optional[datetime] = Field(default=None, description="更新时间")
    created_by: Optional[str] = Field(default=None, description="创建人")
    
    @field_validator('auto_reject_threshold')
    @classmethod
    def validate_thresholds(cls, v, info):
        if info.data and 'auto_approve_threshold' in info.data and v >= info.data['auto_approve_threshold']:
            raise ValueError('自动拒绝阈值必须小于自动通过阈值')
        return v


class RuleResult(BaseModel):
    """单个规则执行结果."""
    
    rule_id: str = Field(..., description="规则ID")
    rule_name: str = Field(..., description="规则名称")
    matched: bool = Field(..., description="是否匹配")
    score_impact: float = Field(..., description="分数影响")
    message: Optional[str] = Field(default=None, description="执行消息")
    execution_time_ms: float = Field(..., description="执行时间（毫秒）")


class AIAnalysisResult(BaseModel):
    """AI分析结果模型."""
    
    # 提取信息
    extracted_info: Dict[str, Any] = Field(default_factory=dict, description="提取的信息")
    confidence_scores: Dict[str, float] = Field(default_factory=dict, description="置信度分数")
    
    # AI评估
    ai_recommendation: str = Field(..., description="AI推荐结果")
    ai_reasoning: str = Field(..., description="AI推理过程")
    risk_assessment: Dict[str, Any] = Field(default_factory=dict, description="风险评估")
    
    # 模型信息
    model_name: str = Field(..., description="使用的模型名称")
    model_version: Optional[str] = Field(default=None, description="模型版本")
    processing_time_ms: float = Field(..., description="处理时间（毫秒）")


class AuditResult(BaseModel):
    """审核结果数据模型."""
    
    # 基础信息
    result_id: str = Field(default_factory=lambda: str(uuid.uuid4()), description="结果ID")
    request_id: str = Field(..., description="对应的请求ID")
    
    # 审核决策
    decision: AuditDecision = Field(..., description="审核决策")
    final_score: float = Field(..., description="最终得分", ge=0, le=100)
    confidence_level: float = Field(..., description="置信度", ge=0, le=1)
    
    # 审核详情
    reasons: List[str] = Field(default_factory=list, description="审核原因列表")
    conditions: Optional[List[str]] = Field(default=None, description="条件列表")
    suggestions: Optional[List[str]] = Field(default=None, description="建议列表")
    
    # 规则执行结果
    rule_results: List[RuleResult] = Field(default_factory=list, description="规则执行结果")
    
    # AI分析结果
    ai_analysis: Optional[AIAnalysisResult] = Field(default=None, description="AI分析结果")
    
    # 审核元信息
    auditor_type: AuditorType = Field(default=AuditorType.AI_SYSTEM, description="审核者类型")
    auditor_id: Optional[str] = Field(default=None, description="审核者ID")
    standard_used: Optional[str] = Field(default=None, description="使用的审核标准ID")
    
    # 处理信息
    processing_time_ms: float = Field(..., description="处理时间（毫秒）")
    created_at: datetime = Field(default_factory=datetime.now, description="创建时间")
    
    # 附加信息
    metadata: Optional[Dict[str, Any]] = Field(default=None, description="元数据")


class AuditLog(BaseModel):
    """审核日志模型."""
    
    # 日志基础信息
    log_id: str = Field(default_factory=lambda: str(uuid.uuid4()), description="日志ID")
    request_id: str = Field(..., description="请求ID")
    
    # 操作信息
    action: str = Field(..., description="操作动作")
    action_details: Optional[Dict[str, Any]] = Field(default=None, description="操作详情")
    
    # 执行信息
    executor_type: str = Field(..., description="执行者类型")
    executor_id: Optional[str] = Field(default=None, description="执行者ID")
    
    # 结果信息
    success: bool = Field(..., description="是否成功")
    error_message: Optional[str] = Field(default=None, description="错误消息")
    
    # 时间信息
    timestamp: datetime = Field(default_factory=datetime.now, description="时间戳")
    execution_duration_ms: Optional[float] = Field(default=None, description="执行时长（毫秒）")
    
    # 上下文信息
    context: Optional[Dict[str, Any]] = Field(default=None, description="执行上下文")


# API响应模型
class AuditRequestResponse(BaseResponse):
    """审核请求响应模型."""
    
    request_id: str = Field(..., description="请求ID")
    status: str = Field(..., description="请求状态")
    estimated_completion_time: Optional[datetime] = Field(default=None, description="预计完成时间")


class AuditResultResponse(BaseResponse):
    """审核结果响应模型."""
    
    result: AuditResult = Field(..., description="审核结果")
    recommendations: Optional[List[str]] = Field(default=None, description="后续建议")


class AuditHistoryResponse(BaseResponse):
    """审核历史响应模型."""
    
    total_count: int = Field(..., description="总数量")
    page_size: int = Field(..., description="页面大小")
    current_page: int = Field(..., description="当前页")
    results: List[AuditResult] = Field(..., description="审核结果列表")


class AuditStandardResponse(BaseResponse):
    """审核标准响应模型."""
    
    standards: List[AuditStandard] = Field(..., description="审核标准列表")


class AuditStatsResponse(BaseResponse):
    """审核统计响应模型."""
    
    total_requests: int = Field(..., description="总请求数")
    approved_count: int = Field(..., description="通过数量")
    rejected_count: int = Field(..., description="拒绝数量")
    pending_count: int = Field(..., description="待审核数量")
    average_processing_time_ms: float = Field(..., description="平均处理时间（毫秒）")
    approval_rate: float = Field(..., description="通过率")
    
    # 时间统计
    stats_by_date: Optional[Dict[str, Dict[str, int]]] = Field(default=None, description="按日期统计")
    stats_by_classroom: Optional[Dict[str, Dict[str, int]]] = Field(default=None, description="按教室统计")


# 批量操作模型
class BatchAuditRequest(BaseModel):
    """批量审核请求模型."""
    
    requests: List[AuditRequest] = Field(..., description="审核请求列表", max_items=100)
    standard_id: Optional[str] = Field(default=None, description="使用的审核标准ID")
    priority_override: Optional[int] = Field(default=None, description="优先级覆盖")


class BatchAuditResponse(BaseResponse):
    """批量审核响应模型."""
    
    batch_id: str = Field(..., description="批次ID")
    total_requests: int = Field(..., description="总请求数")
    successful_count: int = Field(..., description="成功处理数量")
    failed_count: int = Field(..., description="失败处理数量")
    results: List[AuditResult] = Field(..., description="审核结果列表")
    errors: Optional[List[Dict[str, str]]] = Field(default=None, description="错误列表")